package com.erp.auto.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.auto.api.domain.ErpAutoSellerStoreConfig;
import com.erp.auto.domain.ErpAutoViolationInfo;
import com.erp.auto.domain.ErpAutoViolationRecord;
import com.erp.auto.domain.dto.ErpSellerViolationPointsDto;
import com.erp.auto.mapper.ErpAutoSellerStoreConfigMapper;
import com.erp.auto.mapper.ErpAutoViolationInfoMapper;
import com.erp.auto.mapper.ErpAutoViolationRecordMapper;
import com.erp.auto.service.ErpAutoViolationInfoService;
import com.erp.auto.service.ErpAutoViolationRecordService;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 自动化违规信息
 *
 * @author WXX
 * @date 2024-01-11 09:41:14
 */
@Service
@AllArgsConstructor
public class ErpAutoViolationInfoServiceImpl implements ErpAutoViolationInfoService {

    private final ErpAutoViolationInfoMapper erpAutoViolationInfoMapper;
    private final ErpAutoSellerStoreConfigMapper sellerStoreConfigMapper;
    private final ErpAutoViolationRecordMapper erpAutoViolationRecordMapper;
    private final ErpAutoViolationRecordService violationRecordService;
    private final RemoteSellerStoreService sellerStoreService;
    private final RestTemplate restTemplate;

    @Override
    public int saveErpAutoViolationInfo(ErpAutoViolationInfo info) {
        ErpAutoViolationInfo erpAutoViolationInfo = erpAutoViolationInfoMapper.selectById(info);
        if (erpAutoViolationInfo == null) {
            info.setCreateTime(new Date());
            info.setUpdateTime(new Date());
            return erpAutoViolationInfoMapper.insert(info);
        }
        info.setUpdateTime(new Date());
        return erpAutoViolationInfoMapper.updateById(info);
    }

    @Override
    public int selectScoreByStoreId(Long storeId) {
        ErpAutoViolationInfo violationInfo = erpAutoViolationInfoMapper.selectOne(new LambdaQueryWrapper<ErpAutoViolationInfo>().eq(ErpAutoViolationInfo::getStoreCn, storeId.toString()));
        if (violationInfo == null) {
            return 0;
        }
        int score = 0;
        Integer violationType1Point = violationInfo.getViolationType1Point();
        Integer violationType2Point = violationInfo.getViolationType2Point();
        Integer violationType3Point = violationInfo.getViolationType3Point();
        Integer violationType4Point = violationInfo.getViolationType4Point();
        score = violationType1Point + violationType2Point + violationType3Point + violationType4Point;
        return score;
    }

    @Override
    public ErpAutoViolationInfo getViolationByStoreId(Long storeId) {
        return erpAutoViolationInfoMapper.selectOne(new LambdaQueryWrapper<ErpAutoViolationInfo>()
                .eq(ErpAutoViolationInfo::getStoreCn, storeId));
    }

    @Override
    public void pullViolationInfo() {
        // 获取自动化店铺
        List<ErpAutoSellerStoreConfig> sellerStoreList = sellerStoreConfigMapper.selectList(new LambdaQueryWrapper<ErpAutoSellerStoreConfig>().eq(ErpAutoSellerStoreConfig::getStatus, 1));
        Map<String, Object> map = new HashMap<>();
        for (ErpAutoSellerStoreConfig erpAutoSellerStoreConfig : sellerStoreList) {
            Long storeId = erpAutoSellerStoreConfig.getStoreId();
            // 获取店铺cookie
            String cookie = sellerStoreService.getCookieByStoreId(storeId);
            if (cookie == null)
                continue;
            String channelId = sellerStoreService.getChannelByStoreId(storeId);
            if (channelId == null)
                continue;
            map = new HashMap<>();
            map.put("cookie_str", cookie);
            map.put("channelId", channelId);
            ResponseEntity<String> responseEntity = null;
            try {
                responseEntity = restTemplate.postForEntity("http://47.94.131.193:8000/illegal/list", new JSONObject(map), String.class);
            } catch (Exception e) {
                ErpAutoViolationRecord erpAutoViolationRecord = new ErpAutoViolationRecord();
                erpAutoViolationRecord.setViolationNo(System.currentTimeMillis() + "");
                String message = e.getMessage();
                System.out.println("\n" + message);
                erpAutoViolationRecord.setViolationType(message);
                erpAutoViolationRecord.setStoreCn(storeId.toString());
                erpAutoViolationRecord.setIsDownShelf(1);
                erpAutoViolationRecord.setCreateTime(new Date());
                erpAutoViolationRecord.setDownShelfRemark("异常信息无需下架");
                violationRecordService.saveViolationRecord(erpAutoViolationRecord);
                continue;
            }
            String body = responseEntity.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            Integer code = jsonObject.getInteger("code");
            if (code != 200) {
                continue;
            }
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray points = data.getJSONArray("points");
            // 保存 店铺记分/计次情况
            if (points.size() != 0) {
                ErpAutoViolationInfo violationInfo = new ErpAutoViolationInfo();
                ErpAutoViolationInfo erpAutoViolationInfo = erpAutoViolationInfoMapper.selectOne(new LambdaQueryWrapper<ErpAutoViolationInfo>().eq(ErpAutoViolationInfo::getStoreCn, storeId));
                if (erpAutoViolationInfo != null) {
                    violationInfo = erpAutoViolationInfo;
                }
                violationInfo.setStoreCn(storeId.toString());
                violationInfo.setUpdateTime(new Date());
                List<ErpSellerViolationPointsDto> pointsDtoList = JSONObject.parseArray(points.toJSONString(), ErpSellerViolationPointsDto.class);
                for (ErpSellerViolationPointsDto dto : pointsDtoList) {
                    String name = dto.getName();
                    switch (name) {
                        case "PRODUCT_QUALITY":
                            violationInfo.setViolationType1(dto.getValue());
                            violationInfo.setViolationType1Point(dto.getPointValue());
                            break;
                        case "PROHIBITED_PRODUCT_AND_IPR":
                            violationInfo.setViolationType2(dto.getValue());
                            violationInfo.setViolationType2Point(dto.getPointValue());
                            break;
                        case "TRADE_AND_OTHER":
                            violationInfo.setViolationType3(dto.getValue());
                            violationInfo.setViolationType3Point(dto.getPointValue());
                            break;
                        case "SERIOUS_IPR":
                            violationInfo.setViolationType4(dto.getValue());
                            violationInfo.setViolationType4Point(dto.getPointValue());
                            break;
                    }
                }
                saveErpAutoViolationInfo(violationInfo);
            }
            // 保存记录
            JSONArray illegalArray = data.getJSONArray("illegal_list");
            if (illegalArray.size() != 0) {
                ErpAutoViolationRecord record = new ErpAutoViolationRecord();
                for (int i = 0; i < illegalArray.size(); i++) {
                    JSONObject illegal = illegalArray.getJSONObject(i);
                    // 修改或保存
                    Long punishId = illegal.getLong("punishId");
                    record.setViolationNo(punishId.toString());
                    ErpAutoViolationRecord erpAutoViolationRecord = erpAutoViolationRecordMapper.selectOne(new LambdaQueryWrapper<ErpAutoViolationRecord>()
                            .eq(ErpAutoViolationRecord::getViolationNo, punishId)
                            .eq(ErpAutoViolationRecord::getStoreCn, storeId));
                    if (erpAutoViolationRecord != null) {
                        record = erpAutoViolationRecord;
                    }
                    record.setStoreCn(storeId.toString());
                    String subType = illegal.getString("subType");
                    record.setViolationType(subType);
                    JSONArray assetTypes = illegal.getJSONArray("assetTypes");
                    record.setViolationObject(assetTypes.toJSONString());
                    Long beginTime = illegal.getLong("beginTime");
                    record.setPunishTime(new Date(beginTime));
                    Long expireTime = illegal.getLong("expireTime");
                    if (expireTime != null)
                        record.setExpireTime(new Date(expireTime));
                    Integer pointScore = illegal.getInteger("pointScore");
                    record.setPointOrCount(pointScore);
                    String punishReason = illegal.getString("punishReason");
                    record.setPunishReason(punishReason);
                    String punishRule = illegal.getString("punishRule");
                    record.setPunishBasis(punishRule);
                    JSONArray punishInfluences = illegal.getJSONArray("punishInfluences");
                    String showStatus = illegal.getString("showStatus");
                    record.setPunishStatus(showStatus);
                    if (punishInfluences.size() != 0) {
                        record.setViolationImpact(punishInfluences.toJSONString());
                    }
                    // 违规商品
                    String productIds = "";
                    String productImg = "";
                    JSONArray assets = illegal.getJSONArray("assets");
                    for (int i1 = 0; i1 < assets.size(); i1++) {
                        JSONObject jsonObject1 = assets.getJSONObject(i1);
                        // 违规商品id
                        productIds = productIds + jsonObject1.getString("assetId") + ";";
                        // 违规商品主图
                        productImg = productImg + jsonObject1.getString("assetImgUrl") + ";";
                    }
                    if (productIds.length() != 0)
                        record.setViolationProductIds(productIds.substring(0, productIds.length() - 1));
                    if (productImg.length() != 0)
                        record.setViolationProductPic(productImg.substring(0, productImg.length() - 1));

                    String warmPrompt = illegal.getString("warmPrompt");
                    record.setTips(warmPrompt);
                    violationRecordService.saveViolationRecord(record);

                    // 保存完之后看是否违规
                    ErpAutoViolationRecord autoViolationRecord = erpAutoViolationRecordMapper.selectById(record.getId());
                    if (autoViolationRecord == null) {
                        continue;
                    }
                    if (autoViolationRecord.getIsDownShelf() != 0) {
                        continue;
                    }
//                    Boolean violationKeyword = violationKeywordsMapper.isViolationKeyword(autoViolationRecord.getViolationType());
                    // 违规全网下架
                    map = new HashMap<>();
                    String violationNo = autoViolationRecord.getViolationNo();
                    map.put("violationNo", violationNo);
                    String violationProductIds = autoViolationRecord.getViolationProductIds();
                    List<String> productIdList = Arrays.stream(violationProductIds.split(";")).collect(Collectors.toList());
                    for (String productStr : productIdList) {
                        Long productId = Long.parseLong(productStr);
                        map.put("aeProductId", productId);
                        ResponseEntity<String> responseEntity1 = restTemplate.postForEntity("https://pbb2c.com/erp-api/gather/productUnifiedTakedown/autoUnifiedTakeDown", map, String.class);
                        JSONObject jsonObject1 = JSONObject.parseObject(responseEntity1.getBody());
                        if (responseEntity1.getStatusCode().value() != 200) {
                            autoViolationRecord.setIsDownShelf(2);
                            autoViolationRecord.setDownShelfRemark(productStr + "\n" + jsonObject1.getString("msg"));
                            violationRecordService.saveViolationRecord(autoViolationRecord);
                            break;
                        }
                        Integer code1 = jsonObject1.getInteger("code");
                        if (code1 != 200) {
                            // 下架失败
                            autoViolationRecord.setIsDownShelf(2);
                            autoViolationRecord.setDownShelfRemark(productStr + "\n" + jsonObject1.getString("msg"));
                            violationRecordService.saveViolationRecord(autoViolationRecord);
                            break;
                        }
                        else {
                            autoViolationRecord.setIsDownShelf(1);
                            autoViolationRecord.setDownShelfRemark(jsonObject1.getString("msg"));
                            violationRecordService.saveViolationRecord(autoViolationRecord);

                        }
                    }
                }
            }
        }
    }
}
